<template>
  <view id="home">
    <view class="top-title" :style="{height:customBar+'px',paddingTop:statusBar+'px'}">
      <view class="top-title-back" @tap="goHome">
        <image src="../../image/back4.png" />
      </view>
      <view class="top-title-t1" style="color:#fff;">建业车生活</view>
    </view>
    <swiper class="swapper" autoplay="true">
      <view v-for="(item,index) in imgUrlsAds" :key="index" class="block">
        <swiper-item class="slide-image">
          <image :src="item" @tap="goDetail" />
        </swiper-item>
      </view>
    </swiper>
    <!-- <swiper class="swapper" autoplay="true" v-else>
      <view v-for="(item,index) in imgUrls" :key="index" class="block">
        <swiper-item class="slide-image">
          <image :src="item"/>
        </swiper-item>
      </view>
    </swiper>-->
    <image src="../../image/btn.png" class="btn" @tap="goDetail" />
    <!-- <view class="nav-box">
      <navigator url="../openCard/maps?chargType=2" hover-class="none" class="nav-box-a">
        <image :src="imgUrl+'/home/icon1.png'" />
        <text>储值卡</text>
      </navigator>
      <navigator url="../cardManage/card" open-type="redirect" hover-class="none" class="nav-box-a">
        <image :src="imgUrl+'/home/icon2.png'" />
        <text>我的卡券</text>
      </navigator>
      <navigator
        url="../trafficManage/paySuccess?parkId=3"
        open-type="redirect"
        hover-class="none"
        class="nav-box-a"
      >
        <image :src="imgUrl+'/home/icon3.png'" />
        <text>支付成功</text>
      </navigator>
      <navigator
        url="../cardManage/orderList"
        open-type="redirect"
        hover-class="none"
        class="nav-box-a"
      >
        <image :src="imgUrl+'/home/icon4.png'" />
        <text>我的订单</text>
      </navigator>
    </view> -->

    <swiper
      autoplay="true"
      vertical="false"
      style="height:80rpx;margin-top:40rpx"
      v-if="delayOrder.length>0"
    >
      <view v-for="(item,index) in delayOrder" :key="index">
        <swiper-item>
          <view class="info">
            <image src="../../image/home/warn.png" class="info-img1" />
            <view class="info-text" v-if="item.type=='1'">
              月租卡
              <text>有效期剩余:{{item.timeDay}}天</text>
            </view>
            <view class="info-text" v-if="item.type=='2'">储值卡剩余:{{item.accountBalance}}元</view>
            <view class="info-box" @tap="goRecharge(item)">
              <text>延期续费</text>
            </view>
          </view>
        </swiper-item>
      </view>
    </swiper>
    <view style="height:30rpx" v-else></view>
    <view class="box">
      <navigator url="../openCard/maps?chargType=1" hover-class="none">
        <image :src="imgUrl+'/home11.png'" class="img1" />
      </navigator>
      <navigator url="../openCard/maps?chargType=2" hover-class="none">
        <image :src="imgUrl+'/home22.png'" class="img1" style="margin-left:8rpx;margin-right:8rpx" />
      </navigator>
      <navigator url="../cardManage/card" hover-class="none">
        <image :src="imgUrl+'/home3.png'" class="img1" />
      </navigator>
    </view>
    <view id="keysPosition">
      <view class="title-p1">停车缴费</view>
      <key-board
        :carNum="carNum"
        :resetPlate="resetPlate"
        @onOk="onOk"
        @keyBoardShow="keyBoardShow"
        :showKeyboard="false"
        bind:onCancel="onCancel"
        id="keyBoard"
      />
      <view class="cpList">
        <view
          @tap="plateReset(item.carNo)"
          v-for="(item,index) in cpList"
          :key="index"
        >{{item.carNo}}</view>
      </view>
    <view class="btn-submit" @tap="parkingData">查询</view>
    </view>
    <view v-if="isError">
      <view class="panel-black"></view>
      <view class="panel-box">
        <view class="panel-box-t1">提示</view>
        <view class="panel-box-t2">{{errorMsg}}</view>
        <view class="panel-box-btn" @tap="isError=!isError">确定</view>
      </view>
    </view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import "./home.less";
//import authorize from "../../authorize";
import keyBoard from "../../components/keyBoard/keyBoard.vue";
import { setGlobalData, getGlobalData } from "../../globalData.js";
import { request } from "../../util/axios.js";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
export default {
  name: "home",
  data() {
    return {
      imgUrlsAds: [require("../../image/home/banner2.jpg")],
      imgUrls: [],
      isAds: false,
      current: 0,
      showKeyboard: false,
      plate: "", //车牌号
      resetPlate: [], //历史车辆点击录入
      cpList: [],
      cardList: [],
      delayOrder: [],
      parkingCode: "",
      channelCode: "",
      errorMsg: "",
      isError: false,
      statusBar: 0, //状态栏高度
      customBar: 0, //胶囊按钮高度
      isAds: false,
      isClickKeys: false,
      apiBaseUrl: process.env.IOParking.API_HOST, //请求头部
      imgUrl: process.env.IOParking.IMG_URL
    };
  },
  //mixins:[authorize],
  components: { keyBoard },
  mounted() {
    Taro.getSystemInfo({
      success: res => {
        this.statusBar = res.statusBarHeight; //状态栏高度
        let custom = Taro.getMenuButtonBoundingClientRect(); //菜单按钮
        this.customBar = custom.height + 8;
      }
    });
  },

  onLoad: function(options) {
    console.log("参数:", options);
    let that = this;
    if (options.parkingCode) {
      //体验开发版本扫码获得参数
      console.log("体验扫码参数:", options);
      that.parkingCode = options.parkingCode ? options.parkingCode : "";
      that.channelCode = options.channelCode ? options.channelCode : "";
    } else if (options.q) {
      //正式版扫码获得参数
      let qrUrl = decodeURIComponent(options.q);
      that.parkingCode = that.getQueryString(qrUrl, "parkingCode");
      that.channelCode = that.getQueryString(qrUrl, "channelCode");
      console.log(
        "正式扫码parkingCode，channelCode:",
        that.parkingCode,
        that.channelCode
      );
    }
    if (!getGlobalData("openId")) {
      that.wx_login();
    } else {
      console.log("直接获取到用户openId:", getGlobalData("openId"));
      that.initData();
    }
    if (that.parkingCode == "64e93af3-6500-4240-b609-6462142024e2") {
      //凯旋广场换banner
      that.isAds = true;
    } else {
      that.isAds = false;
    }
  },
  created() {
    // this.getPlateList();
    // this.getCardList();
  },
  methods: {
    goDetail() {
      Taro.navigateTo({
        url: "../openCard/maps?chargType=1"
      });
    },
    wx_login() {
      var that = this;
      api
        .getUserInfo({
          scope: "all"
        })
        .then(resp => {
          if (resp.success) {
            console.log("authCode is：", resp.data);
            if (resp.data == "mock") {
              setGlobalData("openId", "oRPxj5ZrsZGRuxTa-UrzEBeLuv-s");
              //setGlobalData("mobile", "17761643218");
              that.getPlateList();
              that.getCardList();
              return;
            }
            that.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
    getInfos(authCode) {
      var that = this;
      Taro.request({
        url: this.apiBaseUrl + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "GET",
        success(res) {
          console.log("获取用户信息：", res.data);
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            setGlobalData("openId", userOpenId);
            setGlobalData("mobile", res.data.data.phoneNum);
            that.getPlateList();
            that.getCardList();
            api.bury("userAuthorizationNum", {
              parkName: "",
              parkId: "",
              time: new Date().valueOf(),
              mobile: getGlobalData("mobile") ? getGlobalData("mobile") : ""
            });
          }
        }
      });
    },
    initData() {
      console.log("首页读取的信息：", {
        mobile: getGlobalData("mobile") || "",
        wxOpenId: getGlobalData("openId")
      });
      this.getPlateList();
      if (getGlobalData("mobile") !== "") {
        this.getCardList();
      }
    },
    closeKeyBord() {
      this.showKeyboard = false;
    },
    //车牌号查询
    onOk(e) {
      this.plate = e;
    },
    keyBoardShow(e) {
      console.log(e);
      if (e) {
        console.log(document.getElementById("keysPosition"));
        document.getElementById("keysPosition").style.paddingBottom = "250px";
       Taro.createSelectorQuery().select('#keysPosition').boundingClientRect(function (rect) {
        console.log(rect)
        // 使页面滚动到底部
        Taro.pageScrollTo({
          scrollTop: rect.bottom
        })
    }).exec()
      } else {
        document.getElementById("keysPosition").style.paddingBottom = "0px";
      }
    },
    //场内码车辆信息查询
    parkingData() {
      if (this.plate < 6) {
        Taro.showToast({
          title: "车牌号不正确",
          icon: "error",
          duration: 1000,
          mask: true
        });
        return;
      }
      Taro.showLoading({
        title: "加载中",
        mask: true
      });
      var that = this;
      var base = this.apiBaseUrl;
      let params = {
        carNo: that.plate,
        parkingCode: that.parkingCode,
        channelCode: that.channelCode
      };
      request("/parkingpayment/getpreparkorderinfo", params).then(res => {
        console.log(res);
        if (res.isSuccess) {
          Taro.navigateTo({
            url:
              "../trafficManage/goPay?carNo=" +
              this.plate +
              "&parkingCode=" +
              that.parkingCode +
              "&isChannle=0"
          });
        } else {
          that.isError = true;
          that.errorMsg = res.message;
        }
      });
    },
    onCancel() {},
    //历史车牌
    getPlateList() {
      var that = this;
      request("/parkingpayment/getcarnorecord").then(res => {
        that.cpList = res.data;
      });
    },
    //用户卡列表
    getCardList() {
      if (!getGlobalData("mobile") || getGlobalData("mobile") == "") {
        return;
      }
      var that = this;
      request("/parkingpayment/getparkingtoken").then(res => {
        console.log(res);
        that.cardList = res.data;
        if(that.cardList.length==1)return
        var times = [];
        that.cardList.forEach((item, index) => {
          if (item.chargId == "1") {
            //当月租卡有效期剩余天数<10时
            var t1 = new Date(item.endDate.replace(/-/g, "/"));
            var t2 = new Date();
            var t = new Date(t1 - t2 + 16 * 3600 * 1000);
            item.timeDay = parseInt(t.getTime() / 1000 / 3600 / 24);
            if (item.timeDay < 11 && item.timeDay > -1) {
              times.push({
                timeDay: parseInt(t.getTime() / 1000 / 3600 / 24),
                id: item.id,
                type: item.type
              });
            }
          } else if (item.chargId == "2") {
            //当储值卡余额<100
            if (item.accountBalance < 51) {
              times.push({
                accountBalance: item.accountBalance,
                id: item.id,
                type: item.type
              });
            }
          }
        });
        that.delayOrder = times;
      });
    },
    goRecharge(e) {
      var cardInfo = e;
      if (cardInfo.type == "1") {
        //月租卡
        Taro.navigateTo({
          url: "../cardManage/monthRecharge?id=" + cardInfo.id
        });
      } else if (cardInfo.type == "2") {
        Taro.navigateTo({
          url: "../cardManage/storeRecharge?id=" + cardInfo.id
        });
      }
    },
    plateReset(e) {
      console.log(e.split(""));
      this.resetPlate = e.split("");
      this.plate=e
    },
    goHome() {
      api.openPage("home");
    },
    //解析链接方法
    getQueryString(url, name) {
      var reg = new RegExp("(^|&|/?)" + name + "=([^&|/?]*)(&|/?|$)", "i");
      var r = url.substr(1).match(reg);
      if (r != null) {
        return r[2];
      }
      return null;
    }
  }
};
</script>

